import {
  Body,
  Controller,
  Get,
  Headers,
  Post,
  Query,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { AdminDto, GetInfo, Register, Update } from './admin.dto';
import { AdminService } from './admin.service';
import { FileInterceptor } from '@nestjs/platform-express';
import {
  getFilePath,
  uploadAvatarConfig,
} from 'src/common/upload/config/upload.Config';
import { Result } from 'src/result/Result';
import { redisUtils } from 'src/utils/redis';
import { Config } from 'src/config';

@Controller('/admin')
export class AdminController {
  constructor(private readonly admin: AdminService) {}

  @Post('/login')
  async Login(@Body() { phone, username, password, captcha, uuid }: AdminDto) {
    return this.admin.Login({ phone, username, password, captcha, uuid });
  }

  @Post('/register')
  async register(@Body() { username, phone, password }: Register) {
    const { message, count } = await this.admin.register({
      username,
      password,
      phone,
    });
    return count ? Result.Ok(null, message) : Result.Error(message);
  }

  @Post('/logout')
  Logout(@Headers('authorization') token: string) {
    return this.admin.Logout(token);
  }

  @UseInterceptors(FileInterceptor('avatarfile', uploadAvatarConfig))
  @Post('/avatar')
  async Upload(@UploadedFile() file: Express.Multer.File) {
    if (!file) return Result.BadRequest('请选择上传图片！');
    return {
      ...Result.ok(),
      imgUrl: getFilePath(file),
    };
  }

  @Post('/update')
  async Update(
    @Headers('Authorization') token: string,
    @Body() UserInfo: Update,
  ) {
    const id = +(await redisUtils.get(`${Config.token.prefix}${token}`));
    return await this.admin.updateAvatar(id, UserInfo);
  }

  @Get('/info')
  async getInfo(@Query() { id }: GetInfo) {
    const user = await this.admin.getInfo(id);
    return user?.id ? Result.ok(user) : Result.Error('该用户不存在');
  }
}
